import {Component} from '@angular/core';

import {
  ViewController,
} from 'ionic-angular';

import {Config} from '../../../../providers/config';

import _ from 'lodash';
import {MarketingOrganizationChooseService} from "./choose.service";

@Component({
  selector: 'page-organization-choose',
  templateUrl: './choose.html',
  providers: [MarketingOrganizationChooseService]
})
export class MarketingOrganizationChoosePage{
	moa_page_name: any = "page-organization-choose";
  moa_page_explain: any = "营销平台 - 机构列表";

  // 列表数据
  listData: any = [];
  //显示标题
  title = '';

  _ = _;
  // 页码
  pageIndex = 1;
  // 是否加载更多
  isLoadMore = true;

  keyWord = null;

  constructor(
              public config: Config,
              public viewCtrl: ViewController,
              public listService: MarketingOrganizationChooseService,
              ) {
     this.loadListData(this.pageIndex, null, null);
  }

  /**
   * [loadListData 加载列表数据]
   * @param {[type]} page           [页码]
   * @param {[type]} infiniteScroll [加载更多组件]
   * @param {[type]} refresher      [下拉刷新组件]
   */
  loadListData(page, infiniteScroll, refresher) {
    this.listService.getOrganizationList(page, this.keyWord).subscribe(data => {
      console.info(data);
      if (data) {
        var dataList = [];
        _.forEach(data, function (i) {
          let d = i.split("|");
          console.log(d);
          dataList.push(d);
        });

        // 如果加载第一页，则清空数据
        if (page == 1) {
          this.isLoadMore = true;
          this.listData = [];
        }
        // 把现有数据和新加载的数据合并
        this.listData = _.concat(this.listData, dataList);
        // 增加搜索索引
        this.pageIndex = this.pageIndex + 1;

        // 如果返回数据少于请求页数，则不再加载更多
        if (data.length < this.config.pageSize) {
          this.isLoadMore = false;
        }
      } else {
        this.listData = [];
        this.isLoadMore = false;
      }
      // complete event
      if (infiniteScroll) {
        infiniteScroll.complete();
      }
      if (refresher) {
        refresher.complete();
      }
    })
  }

  /**
   * [doInfinite 加载更多]
   * @param {[type]} infiniteScroll [事件]
   */
  doInfinite(infiniteScroll) {
    if (this.pageIndex != 1) {
      console.info("-----------infiniteScroll------------");
      console.info(infiniteScroll);
      if (this.isLoadMore) {
        this.loadListData(this.pageIndex, infiniteScroll, null);
      } else {
        infiniteScroll.complete();
      }
    } else {
      infiniteScroll.complete();
    }
  }
  /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
  doRefresh(refresher) {
    this.pageIndex = 1;
    this.isLoadMore = true;
    this.loadListData(this.pageIndex, null, refresher);
  }


  cancel() {
    this.viewCtrl.dismiss("close");
  }

  typeRadioSelected(item) {
    this.viewCtrl.dismiss(item);
  }

  search() {
    this.pageIndex = 1;
    this.loadListData(this.pageIndex, null, null);
  }

}

